package cn.ybz21.hibot.util.shell;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;

import cn.ybz21.hibot.util.FileUtil;
import cn.ybz21.hibot.util.StaticValues;

public class ShellExecutor {

	public ShellExecutor() {

	}

	// 本地执行方法
	public static Process execLocal(String cmd, boolean flag) {
		Process proc = null;
		try {
			proc = Runtime.getRuntime().exec(cmd);
			GobblerThread errorGobbler = new GobblerThread(
					proc.getErrorStream(), "ERROR", flag);
			GobblerThread outputGobbler = new GobblerThread(
					proc.getInputStream(), "OUTPUT", flag);
			errorGobbler.start();
			outputGobbler.start();
			// int exitVal = proc.waitFor();
			// System.out.println("ExitValue: " + exitVal);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return proc;
	}

	// public static void main(String args[]) throws Exception {
	// execLocal("sh /home/ybz/aa.sh");
	// }
}

class GobblerThread extends Thread {
	InputStream is;
	String type;
	BufferedWriter bw;
	boolean flag;

	GobblerThread(InputStream is, String type, boolean flag) {
		this.is = is;
		this.type = type;
		this.flag = flag;
		FileWriter fw = null;
		try {
			fw = new FileWriter(new File(StaticValues.PATH_LOG + "/" + type
					+ ".txt"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		bw = new BufferedWriter(fw);
	}

	public void run() {
		try {
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line = null;
			while ((line = br.readLine()) != null) {
				line = "[" + type + "]" + line;
				if (flag)
					System.out.println(line);
				bw.write(line);
				bw.newLine();
			}
			bw.flush();
			// 关闭缓冲区,同时关闭了fw流对象
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}